package spring.aop;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class AopConfig {

    private final Map<Advice, AopPointcut> pointcutMap = new HashMap<>(10);

    private final Map<String, AopPointcut> advisorFactories = new ConcurrentHashMap<>(10);

    public void addAdvisor(Advice key, AopPointcut value) {
        if (advisorFactories.containsKey(key.getId())) {
            advisorFactories.remove(key.getId(), value);
        }
        pointcutMap.put(key, value);
    }

    public boolean containsFactory(String id) {
        return advisorFactories.containsKey(id);
    }

    public AopPointcut getAopPointcut(String id) {
        return advisorFactories.get(id);
    }

    public void addAdvisorFactory(String key, AopPointcut value) {
        advisorFactories.put(key, value);
    }

    public Map.Entry<Advice, AopPointcut> getAdvisor(String path) {
        for (Map.Entry<Advice, AopPointcut> advisor : pointcutMap.entrySet()) {
            AopPointcut pointcut = advisor.getValue();
            String expression = pointcut.getExp();
            if (path.matches(expression)) {
                return advisor;
            }
        }
        return null;
    }
}
